package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    WeChatProperties weChatProperties;

    @Override
    public User login(UserLoginDTO dto) {
        //使用工具将code发往wexapi
        Map<String, String> urlparam = new HashMap<>();
        urlparam.put("appid", weChatProperties.getAppid());
        urlparam.put("secret", weChatProperties.getSecret());
        urlparam.put("js_code", dto.getCode());
        urlparam.put("grant_type", "authorization_code");
        //获取返回值
        String s = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", urlparam);
        Map<String, String> parse = (Map) JSON.parse(s);
        String openid = parse.get("openid");
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断是否注册
        User user = userMapper.getByOpenId(openid);
        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            Long id = userMapper.addUser(user);
            user.setId(id);
        }
        return user;
    }
}
